package com.lg.cms.controller.admin.article;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.lg.cms.entity.*;
import com.lg.cms.service.*;
import com.lg.cms.utils.SubjectUtil;
import com.lg.cms.utils.UploadFileUtil;
import com.lg.cms.vo.admin.SuperArticleVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description: 文章管理
 * @Author: wuyuhang
 * @create: 2020-10-05 14:33
 * 类型:
 * 文章:封面图片做图片校验
 * 轮播图:做图片校验,默认第一样图做封面
 * 视频:上传的视频做视频后缀校验,无封面
 * <p>
 * (弃用)xx音频:上传的音频做后缀校验,五封面
 */

//@RestController
@Controller
@RequestMapping("/admin/article")
@Api(tags = "文章管理")
public class WYHArticleController {

//    @Autowired
//    ArticleTagsService articleTagsService;
    @Autowired
    CategoryService categoryService;
    @Resource
    UploadFileUtil uploadFileUtil;
    @Autowired
    ArticleService articleService;
    @Autowired
    ArticleTypeService articleTypeService;
    @Autowired
    TagsService tagsService;

    /**
     * 文章列表
     *
     * @param model
     * @return
     */
    @GetMapping("/list")
    public String list(Model model, HttpServletRequest request, Integer categoryId) {
        model.addAttribute("request", request);
        model.addAttribute("user", SubjectUtil.getSuperUser());
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        if(categoryId != null){
            wrapper.eq("category_id", categoryId);
        }
        model.addAttribute("categoryList", categoryService.list(new QueryWrapper<Category>().orderByAsc("sort")));
        List<SuperArticleVO> articleVOList = new ArrayList<>();
        articleService.list(wrapper).forEach(v -> articleVOList.add(articleService.toSuperArticleVO(v)));
        model.addAttribute("articleList", articleVOList);
        model.addAttribute("currentCategoryId", categoryId);
        return "/admin/wyh-test/article/article_list";
    }

    /**
     * 文章新增页
     *
     * @param model
     * @return
     */
    @GetMapping("/add_article")
    public String addArticle(Model model, HttpServletRequest request) {
        model.addAttribute("request", request);
        model.addAttribute("user", SubjectUtil.getSuperUser());
        model.addAttribute("categoryList", categoryService.list(new QueryWrapper<Category>().orderByAsc("sort")));
        model.addAttribute("articleTypeList", articleTypeService.list());
        model.addAttribute("tagsList", tagsService.list());
        return "/admin/wyh-test/article/add_article";
    }

    /**
     * 图片新增页
     *
     * @param model
     * @return
     */
    @GetMapping("/add_image")
    public String addImage(Model model, HttpServletRequest request) {
        model.addAttribute("user", SubjectUtil.getSuperUser());
        model.addAttribute("request", request);
        return "/admin/wyh-test/article/add_image";
    }

    /**
     * 视频新增页
     *
     * @return
     */
    @GetMapping("/add_video")
    public String addVideo(Model model, HttpServletRequest request) {
        model.addAttribute("request", request);
        model.addAttribute("user", SubjectUtil.getSuperUser());
        return "/admin/wyh-test/article/add_video";
    }

    /**
     * 根据文章id获取文章标签列表
     * @param articleId
     * @return
     */
    @GetMapping("/get_tags")
    @ResponseBody
    public R<?> getTags(Integer articleId){
        if(articleId == null){
            return R.failed("文章id为空");
        }
        return R.ok(articleService.getTagsListByArticleId(articleId));
    }

    /**
     * 新增文章,
     * 轮播图, 文章, 视频类型都用此方法
     *
     * @param article
     * @return
     */
    @PostMapping("/add_article")
    @ResponseBody
    @ApiOperation("新增文章")
    public R<?> addArticle(HttpServletRequest request, Article article) {
        SuperUser user = SubjectUtil.getSuperUser();
        article.setSuperUserId(user.getId());
        article.setState(true);
        article.setArticleTypeId(articleTypeService.getArticleTypeMap().get("article"));
        Set<Integer> tagsIdSet = new HashSet<>();
        String[] tagsIdArray = request.getParameterValues("tagsIds[]");
        if (tagsIdArray != null) {
            Arrays.asList(tagsIdArray).forEach(v -> tagsIdSet.add(Integer.parseInt(v)));
        }
        System.out.println(article);
        System.out.println(tagsIdSet);
        return articleService.addArticle(article, tagsIdSet);

    }

    /**
     * 新增文章轮播图
     *
     * @param article
     * @return
     */
    @PostMapping("/add_image")
    @ResponseBody
    public R<?> addImage(Article article, String json) {
        System.out.println(json);
        System.out.println(article);
        article.setState(true);
        /*

        json列表嵌套字典反序列化
        List<Map<String, String>> jsonList = Json.decode(json, List.class);
        List<ImageDTO> ImageDTOList = new ArrayList<>();
        for(Map<String, String> map: jsonList){
            ImageDTO temp = new ImageDTO();
            for(Map.Entry entry: map.entrySet()){
                if(entry.getKey().equals("imageUrl")){
                    temp.setImageUrl((String)entry.getValue());
                }else if(entry.getKey().equals("title")){
                    temp.setTitle((String)entry.getValue());
                }
            }
            ImageDTOList.add(temp);
        }

        ImageDTOList.forEach(System.out::println);
         */
        SuperUser user = SubjectUtil.getSuperUser();
        article.setSuperUserId(user.getId());
        article.setArticleTypeId(articleTypeService.getArticleTypeMap().get("image"));
        article.setCategoryId(categoryService.getCategoryIdMap().get("图片"));
        article.setImageJson(json);
        if(article.getCategoryId() == null){
            return R.failed("请先创建图片栏目再创建轮播图");
        }
        boolean result = articleService.save(article);
        if(!result){
            return R.failed("新增轮播图失败");
        }
        return R.ok(article);
    }

    /**
     * 新增视频文章
     * @param article
     * @return
     */
    @PostMapping("/add_video")
    @ResponseBody
    public R<?> addVideo(Article article){
        article.setState(true);
        System.out.println(article);
        SuperUser user = SubjectUtil.getSuperUser();
        article.setSuperUserId(user.getId());
        article.setCategoryId(categoryService.getCategoryIdMap().get("视频"));
        article.setArticleTypeId(articleTypeService.getArticleTypeMap().get("video"));
        boolean result = articleService.save(article);
        if(!result){
            return R.failed("新增视频失败");
        }
        return R.ok(article);
    }

    /**
     * 获取文章类型列表
     *
     * @return
     */
    public String listArticleType() {
        return null;
    }

    /**
     * 上传图片, 使用ckeditor编辑器
     * 做图片后缀验证
     *
     * @param upload
     * @return uploaded: 0, 1(成功1, 失败0)
     * fileName: (文件名)
     * url: (文件访问路径)
     */
    @PostMapping("/upload_ckeditor")
    @ResponseBody
    public CKEditorResponse uploadCKEditor(MultipartFile upload) {
        MultipartFile file = upload;
        if (file == null) {
            return new CKEditorResponse(0, null, null, "文件为空");
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!articleService.getTypeMap().get("image").contains(suffix)) {
            return new CKEditorResponse(0, null, null, "类型不匹配");
        }

        R<String> r = uploadFileUtil.uploadAuto(file);
        if (r.getCode() == 0) {
            return new CKEditorResponse(1, file.getOriginalFilename(), r.getData(), "成功");
        } else {
            return new CKEditorResponse(0, null, null, r.getMsg());
        }
    }

    /**
     * 上传图片, 使用普通文件上传
     * 做图片后缀验证
     *
     * @param file
     * @return code: 0, -1(0成功, 失败-1)
     * dat: (文件访问url)
     * msg: (错误信息)
     */
    @PostMapping("/upload_image")
    @ResponseBody
    public R<?> uploadImage(MultipartFile file) {
        if (file == null) {
            return R.failed("文件为空");
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!articleService.getTypeMap().get("image").contains(suffix)) {
            return R.failed("文件格式错误");
        }
        return uploadFileUtil.uploadAuto(file);
    }

    /**
     * 上传视频, 使用普通文件上传
     * 做视频后缀验证
     *
     * @param file
     * @return code: 0, -1(0成功, 失败-1)
     * dat: (文件访问url)
     * msg: (错误信息)
     */
    @PostMapping("upload_video")
    @ResponseBody
    public R<?> uploadVideo(MultipartFile file) {
        if (file == null) {
            return R.failed("文件为空");
        }
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!articleService.getTypeMap().get("video").contains(suffix)) {
            return R.failed("文件格式错误");
        }
        return uploadFileUtil.uploadAuto(file);


    }

    /**
     * ckeditor传输对象
     */
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private static class CKEditorResponse {
        /**
         * 1成功, 0失败
         */
        private Integer uploaded;

        private String fileName;

        private String url;
        private String msg;
    }
}
